# -*- coding: utf-8 -*-

import os
import json
import logging as log
import com.maycur.gateway.common.locust_global as the_g
from com.maycur.gateway.testcase.openapi.department_task import DepartmentTask
from com.maycur.gateway.testcase.openapi.role_task import RoleTask

from common.login_helper import LoginUtils
from common.base_entity import EnvInfo, OpenApiOrgInfo
from com.maycur.gateway.common.account_manager import AccountManager

from locust import FastHttpUser, between, events


@events.test_start.add_listener
def on_test_start(**args):
    log.info('OpenAPI stress test is start ^_^_^_^')


@events.test_stop.add_listener
def on_test_stop(**args):
    log.info('OpenAPI stress test is ended ^_^_^_^')


@events.request_success.add_listener
def process_success_requests(request_type, name, response_time, response_length, **kwargs):
    print(f'success Type: {request_type}, Name: {name}, Response_Time: {response_time}, Length: {response_length}')


class OpenApiUser(FastHttpUser, OpenApiOrgInfo):
    headers: json
    headers_with_content_type: json

    def login_if_necessary(self, org_info):
        if org_info.select_ent_code is None or org_info.select_ent_code == '':
            login_util = LoginUtils()
            pair = login_util.openapi_login(org_info.app_code, org_info.app_secret, env)
            if pair is not None:
                print(f'login info, ent_code: {pair[0]}, token_id: {pair[1]}')
                self.select_ent_code = pair[0]
                self.token_id = pair[1]

    def on_start(self):
        if account_manager.open_api_org_queue.empty():
            log.info('no available maycur OpenAPI org anymore, stop it')
            self.stop(True)
        org_info = account_manager.open_api_org_queue.get()
        log.info(f'org_name={org_info.org_name}, app_code = {org_info.app_code}, secret = {org_info.app_secret}')
        self.login_if_necessary(org_info)
        account_manager.open_api_org_queue.put(org_info)

        self.tasks = [DepartmentTask, RoleTask]

    def on_stop(self):
        print('test finished')

    wait_time = between(0.5, 2)


env = EnvInfo.NG_SIT
the_g.env = env
account_manager = AccountManager()
account_manager.file_load_open_api_orgs()
if __name__ == '__main__':
    os.system(f'locust -f open_api_stress_test.py --host={env.value.app_host}')

